import React, { useEffect, useMemo, useState } from 'react';
import { Col, Row } from 'antd';
import { useModel } from "umi"
import { SelectableGroup, createSelectable } from './../../ReactSelectable';
import styles from './index.less'


function Cell({ children, selected, style, editable, refreshconfig, selectableKey }) {
    const { initialState, setInitialState } = useModel("@@initialState");

    if (editable) {
        return <div
            suppressContentEditableWarning
            contentEditable={editable}
            data-no-dnd="true"
            className={selected ? styles.active : styles.cell} style={{ ...style }}
            onInput={(e) => {
                let value = e.target?.innerText ?? "";
                setInitialState(s => ({
                    ...s,
                    editext: {
                        id: selectableKey,
                        value: value
                    }
                }))
            }}

        >
            {children}
        </div>
    } else {
        return <div
            className={selected ? styles.active : styles.cell} style={{ ...style }}>
            {children}
        </div>
    }

}

const Cells = createSelectable(Cell)

function Atable({ checkedId, id, setconfig, style, rowcol, dataSource, percent, edit }) {
    const { borderColor, borderWidth, align, bodybg, bodysize, bodycolor } = style;
    const { initialState, setInitialState } = useModel("@@initialState");
    const { selectedKeys, editext } = initialState;
    const [editable, seteditable] = useState('');
    const gridTemplateColumns = useMemo(() => {
        let dis = new Array(rowcol.col).fill("1fr");
        return dis.join(" ");
    }, [rowcol])


    useEffect(() => {
        setInitialState(s => ({ ...s, selectedKeys: [], selectedIndexArr: [] }));
    }, [checkedId])

    //更新tabs
    function refreshconfig(fn) {
        setconfig((config) => {
            let newconfig = JSON.parse(JSON.stringify(config));
            newconfig.pages = newconfig?.pages?.map?.(item => {
                if (item.active) {
                    item.components = item?.components?.map?.(its => {
                        if (its.id == id) {
                            return fn?.(its);
                        }
                        return its;
                    })
                }
                return item
            });
            return newconfig
        });
    }

    return (
        (edit && checkedId == id) ?
            <SelectableGroup
                className={styles.container}
                onSelection={(val) => {
                    let indexarr = []
                    dataSource.map((it, i) => {
                        if (val.indexOf(it.id) != -1) {
                            if (it.max) {
                                //已被合并的单元格处理
                                indexarr.push(it.min);
                                indexarr.push(it.max);
                            } else {
                                //未被合并的单元格处理
                                indexarr.push(i + 1);
                            }
                        }
                    })
                    console.log(val);
                    setInitialState(s => ({ ...s, selectedKeys: val, selectedIndexArr: indexarr }));
                }}
                percent={percent}
                enabled={!editable}
            >
                <div
                    className={styles.table}
                    id="fixtable"
                    style={{
                        gridTemplateColumns,
                        backgroundColor: borderColor,
                        gap: borderWidth,
                        padding: borderWidth
                    }}
                >
                    {
                        dataSource && dataSource.map((it, i) => {
                            return <div
                                key={it.id}
                                onMouseLeave={() => {
                                    //同步修改内容
                                    if (editext) {
                                        refreshconfig(its => {
                                            its.dataSource = its.dataSource.map((it, i) => {
                                                if (it.id == editext.id) {
                                                    it.content = editext.value
                                                }
                                                return it
                                            })
                                            return its
                                        })
                                    } else {

                                    }
                                }}
                                onClick={() => {
                                    let res = [it.id],
                                        ins = [i + 1];

                                    if (editable != it.id) {
                                        seteditable(null)
                                    }

                                    setInitialState(s => ({
                                        ...s,
                                        selectedKeys: res,
                                        selectedIndexArr: ins,
                                        editext: {
                                            id: it.id,
                                            value: it.content
                                        }
                                    }));
                                }}
                                onDoubleClick={() => {
                                    seteditable(it.id)
                                }}
                                style={it.startrow ? {
                                    gridArea: `${it.startrow} / ${it.startcol} / span ${it.rowNum} / span ${it.columnNum}`,
                                    display: it.style.display ?? "flex"
                                } : {
                                    display: it.style.display ?? "flex"
                                }}
                            >
                                <Cells
                                    key={it.id}
                                    selected={selectedKeys.indexOf(it.id) > -1}
                                    selectableKey={it.id}
                                    style={{ justifyContent: align, ...(it["style"] ?? {}) }}
                                    editable={editable == it.id}
                                    refreshconfig={refreshconfig}
                                >
                                    {
                                        it["content"]
                                    }
                                </Cells>
                            </div>

                        })
                    }



                </div>
            </SelectableGroup >
            :
            <div
                className={styles.table}
                id="fixtable"
                style={{
                    gridTemplateColumns,
                    backgroundColor: borderColor,
                    gap: borderWidth,
                    padding: borderWidth,
                    borderRadius: style.borderRadius,
                    overflow: "hidden"
                }}
            >
                {
                    dataSource && dataSource.map((it, i) => {
                        return <div
                            key={it.id}
                            style={it.startrow ? {
                                ...it.style,
                                gridArea: `${it.startrow} / ${it.startcol} / span ${it.rowNum} / span ${it.columnNum}`,
                                display: it.style.display ?? "flex"
                            } : {
                                ...it.style,
                                display: it.style.display ?? "flex"
                            }}

                        >
                            <div className={selectedKeys.indexOf(it.id) > -1 ? styles.active : styles.cell} style={{justifyContent: align}}>
                                {
                                    it["content"]
                                }
                            </div>
                        </div>
                    })
                }



            </div>

    );
}

export default Atable;